package com.scholarship.modules.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.scholarship.common.dto.ResultListDto;
import com.scholarship.common.entity.RedisKeys;
import com.scholarship.common.utils.MyDateUtil;
import com.scholarship.common.utils.RedisUtil;
import com.scholarship.modules.admin.dto.*;
import com.scholarship.modules.admin.entity.*;
import com.scholarship.modules.admin.exce.EmptyValueException;
import com.scholarship.modules.admin.mapper.*;
import com.scholarship.modules.admin.service.FeedbackListService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;

/**
 * @Author Z.J.H
 * @create 2021/5/9 13:56
 */
@Service
public class FeedbackListServiceImpl implements FeedbackListService {

    @Autowired
    private AUserInfoMapper aUserInfoMapper;

    @Autowired
    private ARewardFeedbackMapper aRewardFeedbackMapper;

    @Autowired
    private ARewardApplicationMapper aRewardApplicationMapper;

    @Autowired
    private ARewardTypeMapper aRewardTypeMapper;

    @Autowired
    private ARewardTypeDetailMapper aRewardTypeDetailMapper;

    @Autowired
    private ATableInfoMapper aTableInfoMapper;

    @Autowired
    private ADropDownBoxMapper aDropDownBoxMapper;

    @Autowired
    private ACommonMapper aCommonMapper;

    @Autowired
    private RedisUtil redisUtil;

    private static final String[] REWARD = {"rewardType","rewardTypeDetail","tableInfo","dropDownBox"};

    /**
     * 获取申请审核列表查询条件
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, List<String>> getFeedbackQuery() throws Exception {
        String redisKey = RedisKeys.FEEDBACK_QUERY.toString();

        Map<String,List<String>> map = redisUtil.get(redisKey);
        if(map == null) {
            synchronized (this) {
                map = redisUtil.get(redisKey);

                if(map == null) {
                    List<String> years = new ArrayList<>();
                    years.add("所有学年");
                    years.addAll(aUserInfoMapper.listYear());

                    List<String> majors = new ArrayList<>();
                    majors.add("所有专业");
                    majors.addAll(aUserInfoMapper.listMajor());

                    List<String> stuClasses = new ArrayList<>();
                    stuClasses.add("所有班级");
                    stuClasses.addAll(aUserInfoMapper.listStuClass());

                    List<String> submissionTimes = new ArrayList<>();
                    submissionTimes.add("所有年份");
                    submissionTimes.addAll(aRewardFeedbackMapper.listSubmissionTime());

                    List<String> states = new ArrayList<>();
                    states.add("所有状态");
                    states.addAll(aRewardFeedbackMapper.listState());

                    map = new HashMap<>();
                    map.put("year",years);
                    map.put("major",majors);
                    map.put("stuClass",stuClasses);
                    map.put("submissionTime",submissionTimes);
                    map.put("state",states);

                    redisUtil.set(redisKey,map,30L);
                }
            }
        }
        return map;
    }

    /**
     * 查询所有审核信息
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public ResultListDto<FeedbackListDto> listAllFeedback(Integer pageNum, Integer pageSize) throws Exception {
        //使用PageHelper实现分页
        PageHelper.startPage(pageNum,pageSize);
        List<FeedbackListDto> list = aRewardFeedbackMapper.listFeedback();
        PageInfo<FeedbackListDto> pageInfo = new PageInfo<>(list);

        return new ResultListDto<FeedbackListDto>(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 根据查询条件查询审核信息
     * @param pageNum
     * @param pageSize
     * @param feedbackQueryDto
     * @return
     * @throws Exception
     */
    @Override
    public ResultListDto<FeedbackListDto> listFeedbackByQuery(Integer pageNum, Integer pageSize, FeedbackQueryDto feedbackQueryDto) throws Exception {
        //使用PageHelper实现分页
        PageHelper.startPage(pageNum,pageSize);
        List<FeedbackListDto> list = aRewardFeedbackMapper.listFeedbackByQuery(feedbackQueryDto);
        PageInfo<FeedbackListDto> pageInfo = new PageInfo<>(list);

        return new ResultListDto<FeedbackListDto>(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 根据搜索查询审核信息
     * @param pageNum
     * @param pageSize
     * @param searchStr
     * @return
     * @throws Exception
     */
    @Override
    public ResultListDto<FeedbackListDto> listFeedbackBySearch(Integer pageNum, Integer pageSize, String searchStr) throws Exception {
        //使用PageHelper实现分页
        PageHelper.startPage(pageNum,pageSize);
        List<FeedbackListDto> list = aRewardFeedbackMapper.listFeedbackBySearch(searchStr);
        PageInfo<FeedbackListDto> pageInfo = new PageInfo<>(list);

        return new ResultListDto<FeedbackListDto>(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 批量删除选中信息
     * @param userIdList   用户id列表
     * @throws Exception
     */
    @Override
    public void batchDeleteFeedbacks(String[] userIdList) throws Exception {
        for(String userId : userIdList) {
            if(!userId.equals("")) {
                aRewardFeedbackMapper.deleteRewardFeedbackByUserId(userId);
            }
        }
    }

    /**
     * 获取奖学金类型列表
     * @return
     * @throws Exception
     */
    @Override
    public List<RewardTypeDto> listAllRewardType() throws Exception {
        return aRewardTypeMapper.listRewardType();
    }

    /**
     * 获根据奖学金类型id取奖项列表
     * @param typeId
     * @return
     * @throws Exception
     */
    @Override
    public List<RewardTypeDetailDto> listRewardTypeDetailByTypeId(Integer typeId) throws Exception {
        return aRewardTypeDetailMapper.listRewardTypeDetailDtoByTypeId(typeId);
    }

    /**
     * 通过奖项id查询字段列表
     * @param tableId
     * @return
     * @throws Exception
     */
    @Override
    public List<TableInfoDto> listTableInfoByTableId(Integer tableId) throws Exception {
        return aTableInfoMapper.listTableInfoDtoByTableId(tableId);
    }

    /**
     * 通过奖项id和字段类型id查询下拉框列表
     * @param tableId
     * @param fieldId
     * @return
     * @throws Exception
     */
    @Override
    public List<DropDownBox> listDropDownBoxByTableIdAndFieldId(Integer tableId, Integer fieldId) throws Exception {
        return aDropDownBoxMapper.listDropDownBoxByTableIdAndFieldId(tableId,fieldId);
    }

    /**
     * 显示奖学金申请层级表（奖学金类型+奖项+字段+下拉框  +  已填写信息）
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public List<RewardTypeDto> listRewardListAndInformation(String userId) throws Exception {
        Random random = new Random();

        //获取当前年份
        Calendar calendar = Calendar.getInstance();
        String year = String.valueOf(calendar.get(Calendar.YEAR));

        UserInfo userInfo = aUserInfoMapper.getUserInfoByUserId(userId);

        //奖项类型
        List<RewardTypeDto> rewardTypeDtoList = new ArrayList<>();
        if(redisUtil.exists(REWARD[0])) {
            rewardTypeDtoList = (List<RewardTypeDto>) redisUtil.lget(REWARD[0],0, -1);
        }else {
            rewardTypeDtoList = aRewardTypeMapper.listRewardType();
            redisUtil.lset(REWARD[0],rewardTypeDtoList,random.nextInt(30) + 30);
        }

        //奖项
        for(int i = 0;i < rewardTypeDtoList.size();i++) {
            int typeId = rewardTypeDtoList.get(i).getId();
            List<RewardTypeDetailDto> rewardTypeDetailDtoList = new ArrayList<>();
            String rewardTypeDetailKey = REWARD[1] + typeId;
            if(redisUtil.exists(rewardTypeDetailKey)) {
                rewardTypeDetailDtoList = (List<RewardTypeDetailDto>) redisUtil.lget(rewardTypeDetailKey,0, -1);
            }else {
                rewardTypeDetailDtoList = aRewardTypeDetailMapper.listRewardTypeDetailDtoByTypeId(typeId);
                redisUtil.lset(rewardTypeDetailKey,rewardTypeDetailDtoList,random.nextInt(30) + 30);
            }

            //字段
            for(int j = 0;j < rewardTypeDetailDtoList.size();j++) {
                int tableId = rewardTypeDetailDtoList.get(j).getId();
                List<TableInfoDto> tableInfoDtoList = new ArrayList<>();
                String tableInfoKey = REWARD[2] + tableId;
                if(redisUtil.exists(tableInfoKey)) {
                    tableInfoDtoList = (List<TableInfoDto>) redisUtil.lget(tableInfoKey,0, -1);
                }else {
                    tableInfoDtoList = aTableInfoMapper.listTableInfoDtoByTableId(tableId);
                    redisUtil.lset(tableInfoKey,tableInfoDtoList,random.nextInt(30) + 30);
                }

                //加权平均分、四六级、其他
                if(tableId == 1) {
                    tableInfoDtoList.get(0).setValue(userInfo.getScore());
                }else {
                    List<String> fieldList = aTableInfoMapper.listFieldByTableId(tableId);
                    CommonPrizeDto commonPrizeDto = new CommonPrizeDto();
                    commonPrizeDto.setTableName(rewardTypeDetailDtoList.get(j).getTableName());
                    commonPrizeDto.setFields(fieldList);

                    Map<String,Object> rewardMap = aCommonMapper.getStudentReward(userId,commonPrizeDto);

                    //用户保存信息及下拉框
                    for(int k = 0;k < tableInfoDtoList.size();k++) {
                        if(rewardMap != null) {
                            tableInfoDtoList.get(k).setValue(rewardMap.get(tableInfoDtoList.get(k).getAttributeName()));
                        }

                        //如果字段类型为分值下拉框——4
                        if(tableInfoDtoList.get(k).getFieldId().equals(4)) {
                            int fieldId = tableInfoDtoList.get(k).getId();
                            List<DropDownBox> dropDownBoxList = new ArrayList<>();
                            String dropDownBoxKey = REWARD[3] + fieldId;
                            if(redisUtil.exists(dropDownBoxKey)) {
                                dropDownBoxList = (List<DropDownBox>) redisUtil.lget(dropDownBoxKey,0, -1);
                            }else {
                                dropDownBoxList = aDropDownBoxMapper.listDropDownBoxByFieldId(fieldId);
                                redisUtil.lset(dropDownBoxKey,dropDownBoxList,random.nextInt(30) + 30);
                            }

                            tableInfoDtoList.get(k).setDropDownBoxList(dropDownBoxList);
                        }
                    }
                }
                //添加图片保存地址和得分信息
                RewardApplication rewardApplication = aRewardApplicationMapper.getRewardApplicationByUserId(userId,tableId,year);
                if(rewardApplication != null) {
                    rewardTypeDetailDtoList.get(j).addRewardApplication(rewardApplication);
                }

                rewardTypeDetailDtoList.get(j).setTableInfoListDto(tableInfoDtoList);
            }
            rewardTypeDtoList.get(i).setRewardTypeDetailDtoList(rewardTypeDetailDtoList);
        }

        return rewardTypeDtoList;
    }

    /**
     * TODO:显示奖学金申请层级表（奖学金类型+奖项+字段+下拉框）
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public List<RewardTypeDto> listRewardListAndInformationNew(String userId) throws Exception {

        return null;
    }

    /**
     * 保存指定奖项信息
     * @param userId
     * @param rewardTypeDetailDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSelectedRewardTypeDetail(String userId, RewardTypeDetailDto rewardTypeDetailDto)
            throws ParseException,EmptyValueException {

        //用于记录空内容的数量
        Integer emptyNum = 0;

        //获取当前年份
        Calendar calendar = Calendar.getInstance();
        String year = String.valueOf(calendar.get(Calendar.YEAR));

        Map<String,Object> map = new HashMap<>();
        map.put("user_id",userId);

        Iterator iterator = rewardTypeDetailDto.getTableInfoListDto().iterator();
        while (iterator.hasNext()) {
            TableInfoDto tableInfoDto = (TableInfoDto) iterator.next();

            if(tableInfoDto.getValue() == null || tableInfoDto.getValue().toString().equals("")) {
                //如果是老师填写内容，默认可为空
                if(tableInfoDto.getIsTeacherWrite() != 1) {
                    emptyNum++;
                }
                continue;
            }

            //如果是日期类型--2
            if(tableInfoDto.getFieldId().equals(2)) {
                tableInfoDto.setValue(MyDateUtil.UTCToYMD((String) tableInfoDto.getValue()));
            }
            map.put(tableInfoDto.getAttributeName(),tableInfoDto.getValue());
        }

        RewardApplication rewardApplication = new RewardApplication();
        rewardApplication.setUserId(userId);
        rewardApplication.setTableId(rewardTypeDetailDto.getId());
        rewardApplication.setImportYear(year);
        rewardApplication.setFilePath(rewardTypeDetailDto.getValue());
        rewardApplication.setFeedback(rewardTypeDetailDto.getFeedback());
        rewardApplication.setScore(rewardTypeDetailDto.getScore());
        rewardApplication.setState(rewardTypeDetailDto.getState());

        if(emptyNum == 0) {
            if(rewardTypeDetailDto.getIsUploadFile().equals(1) && StringUtils.isBlank(rewardTypeDetailDto.getValue())) {
                throw new EmptyValueException("需提交文件，但文件路径为空");
            }
            aCommonMapper.insertAndUpdateSelectedReward(rewardTypeDetailDto.getTableName(),map);
            aRewardApplicationMapper.insertAndUpdateRewardApplication(rewardApplication);
        }else if(emptyNum == rewardTypeDetailDto.getTableInfoListDto().size()) {
            aCommonMapper.deleteSelectedRewardByUserId(rewardTypeDetailDto.getTableName(),userId);
            aRewardApplicationMapper.deleteRewardApplication(rewardApplication);
        }else {
            throw new EmptyValueException("表单存在空值");
        }
    }

    /**
     * TODO:清空指定奖项信息
     * @param userId
     * @param tableId
     */
    @Override
    public void emptySelectedRewardTypeDetail(String userId, Integer tableId) {

    }

    /**
     * 获取申请详情
     * @param userId
     * @return
     */
    @Override
    public RewardFeedback getApplication(String userId) {
        //获取当前年份
        Calendar calendar = Calendar.getInstance();
        String year = String.valueOf(calendar.get(Calendar.YEAR));

        return aRewardFeedbackMapper.getRewardFeedbackByUserId(userId,year);
    }

    /**
     * TODO:提交申请
     * @param userId
     */
    @Override
    public void submitApplication(String userId) {
        RewardFeedback rewardFeedback = new RewardFeedback();
        rewardFeedback.setUserId(userId);
        rewardFeedback.setSubmissionTime(MyDateUtil.YMDHMS.format(new Date()));
        //rewardFeedback.setState(FeedbackState.NOTAPPROVED.getCode());
        rewardFeedback.setStudentFeedback(null);

        aRewardFeedbackMapper.insertAndUpdateSubmitApplication(rewardFeedback);
    }
}
